/*    */ package scripting.event;
/*    */ 
/*    */ import handling.channel.ChannelServer;
/*    */ import java.util.ArrayList;
/*    */ import java.util.Arrays;
/*    */ import java.util.LinkedHashMap;
/*    */ import java.util.List;
/*    */ import java.util.Map;
/*    */ import java.util.concurrent.atomic.AtomicInteger;
/*    */ import javax.script.Invocable;
/*    */ import javax.script.ScriptEngine;
/*    */ import org.apache.logging.log4j.LogManager;
/*    */ import org.apache.logging.log4j.Logger;
/*    */ import scripting.AbstractScriptManager;
/*    */ 
/*    */ public class EventScriptManager
/*    */   extends AbstractScriptManager {
/* 18 */   private static final Logger log = LogManager.getLogger(EventScriptManager.class.getName());
/* 19 */   private static final AtomicInteger runningInstanceMapId = new AtomicInteger(0);
/* 20 */   private final Map<String, EventEntry> events = new LinkedHashMap<>(), defaultEvents = new LinkedHashMap<>();
/*    */ 
/*    */   
/*    */   public EventScriptManager(ChannelServer cserv, String[] scripts) {
/* 24 */     List<String> strings = Arrays.asList(scripts);
/* 25 */     strings.stream().filter(s -> !s.isEmpty()).forEach(s -> {
/*    */           Invocable iv = getInvocable("event/" + s + ".js", null);
/*    */           if (iv != null) {
/*    */             this.events.put(s, new EventEntry(s, iv, new EventManager(cserv, iv, s)));
/*    */           }
/*    */         });
/*    */   }
/*    */ 
/*    */ 
/*    */ 
/*    */ 
/*    */ 
/*    */ 
/*    */ 
/*    */   
/*    */   public static int getNewInstanceMapId() {
/* 41 */     return runningInstanceMapId.addAndGet(1);
/*    */   }
/*    */   
/*    */   public EventManager getEventManager(String event) {
/*    */     EventEntry entry;
/* 46 */     if (BossEventManager.ISOPEN && BossEventManager.getInstance().canUseDefaultScript(event)) {
/* 47 */       entry = this.defaultEvents.get(event);
/*    */     } else {
/* 49 */       entry = this.events.get(event);
/*    */     } 
/* 51 */     if (entry == null) {
/* 52 */       return null;
/*    */     }
/* 54 */     return entry.em;
/*    */   }
/*    */   
/*    */   public void init() {
/* 58 */     List<EventEntry> events_temp = new ArrayList<>(this.events.values());
/* 59 */     events_temp.addAll(this.defaultEvents.values());
/* 60 */     events_temp.forEach(eventEntry -> {
/*    */           try {
/*    */             ((ScriptEngine)eventEntry.iv).put("em", eventEntry.em);
/*    */             eventEntry.iv.invokeFunction("init", new Object[] { null });
/* 64 */           } catch (Exception ex) {
/*    */             log.error("Error initiating event: " + eventEntry.script + ":" + ex);
/*    */           } 
/*    */         });
/*    */   }
/*    */   
/*    */   public void cancel() {
/* 71 */     for (EventEntry entry : this.events.values())
/* 72 */       entry.em.cancel(); 
/*    */   }
/*    */ }